package com.sg.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sg.common.LgPage;
import com.sg.common.ResponseInfo;
import com.sg.entity.UserInfo;
import com.sg.entity.UserTag;
import com.sg.service.LoginService;
import com.sg.service.UserInfoService;
import com.sg.service.UserTagService;
import com.sg.vo.FlowVO;
import com.sg.vo.UserVO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

@RestController
@RequestMapping("login")
//@CrossOrigin(origins = "*", maxAge = 3600)
public class UserController {


    @Resource
    private UserInfoService userInfoService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private LoginService loginService;
    @Resource
    private UserTagService userTagService;


    private final static String access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
    private final static String appid = "wx23cfbbd94d40395b";
    private final static String secret = "706d3f906037f3cf47d5054a3cd60ecc";
    private final static String grant_type = "authorization_code";
    public final static String TOEKN_KEY = "sg";
    public final static String TOEKN_KEY_REDIS_TOKEN= "login_token:";

    public final static String AUTH_HEADER_NAME = "token";



    @GetMapping("login")
    public ResponseInfo<String> login(String code){
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        map.put("grant_type", grant_type);
        map.put("code", code);
        String s = HttpUtil.get(access_token_url, map);
        JSONObject jsonObject = JSON.parseObject(s);
        if(jsonObject.getString("errcode") != null){
            return ResponseInfo.error(jsonObject.getString("errmsg"), 500);
        }
        String openid = jsonObject.getString("openid");
//        String openid = "o5oXLjrclJ4LJqYf5F1QTJ9f7IbM";
        // 根据openid查询用户信息  若用于已存在则不进行保存
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getOpenid, openid);
        UserInfo one = userInfoService.getOne(wrapper);
        if(one == null){
            one = new UserInfo();
            one.setOpenid(openid);
            userInfoService.save(one);
        }
        return ResponseInfo.success(logined(one));
    }


    @GetMapping("/userList")
    public ResponseInfo<LgPage<UserVO>> userList(Integer page, Integer rows, Integer id){
        PageHelper.startPage(page, rows);
        List<UserVO> list = userInfoService.getInfo(id);
        list.forEach(userVO -> {
           Integer current = userInfoService.getCurrent(userVO.getId());
           userVO.setCurrent(current);
            Integer times = userInfoService.getTimes(userVO.getId());
            userVO.setCount(times);
        });
        LgPage<UserVO> userVOLgPage = LgPage.setPage(list);
        return ResponseInfo.success(userVOLgPage);
    }


    @GetMapping("/flow")
    public ResponseInfo<List<FlowVO>> flow(Integer id){
        List<FlowVO> flowVOS = userInfoService.flow(id);
        return ResponseInfo.success(flowVOS);
    }


    @GetMapping("/hx")
    public ResponseInfo<Boolean> hx(Integer id, Integer sl){
        userInfoService.hx(id, sl);
        return ResponseInfo.success(true);
    }


    @GetMapping("bond")
    public ResponseInfo<Boolean> bond(HttpServletRequest request, String tagId){
        UserInfo loginYh = loginService.getLoginYh(request);
        LambdaQueryWrapper<UserTag> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(UserTag::getTagId, tagId).eq(UserTag::getStatus, 1).eq(UserTag::getUserId,loginYh.getId());
        List<UserTag>  list = userTagService.list(wrapper);
        list.forEach(userTag -> {
            userTag.setStatus("0");
            userTag.setUnbondTime(new Date());
            userTag.setUnbondReason("用户" + loginYh.getId() + "绑定手环"+tagId);
            userTagService.updateById(userTag);
        });

        wrapper.clear();
        wrapper.eq(UserTag::getTagId, tagId).eq(UserTag::getStatus, 1);
        list = userTagService.list(wrapper);
        // 当前用户是否已绑定
        AtomicReference<Boolean> flag = new AtomicReference<>(false);
        list.forEach(userTag -> {
            if(userTag.getUserId() != loginYh.getId()){
                userTag.setStatus("0");
                userTag.setUnbondTime(new Date());
                userTag.setUnbondReason("用户" + loginYh.getId() + "绑定手环");
                userTagService.updateById(userTag);
            } else {
                flag.set(true);
            }
        });
        if(flag.get()){
           return ResponseInfo.success(true);
        }

        UserTag userTag = new UserTag();
        userTag.setUserId(loginYh.getId());
        userTag.setStatus("1");
        userTag.setTagId(tagId);
        userTag.setBondTime(new Date());
        userTagService.save(userTag);
        return ResponseInfo.success(true);
    }


    private String logined(UserInfo one){
        Map<String, Object> map = new HashMap<>();
        map.put("uid",one.getId());
        map.put("date",System.currentTimeMillis());
        String token = JWTUtil.createToken(map, TOEKN_KEY.getBytes());
        // 保存到redis
        stringRedisTemplate.opsForValue().set(TOEKN_KEY_REDIS_TOKEN+token, JSON.toJSONString(one),78, TimeUnit.HOURS);
        return token;
    }



}
